/*
 * @Author: ws
 * @Date: 2023-12-29 09:50:39
 * @email: 458658538@qq.com
 * @LastEditors: ws
 * @LastEditTime: 2024-01-02 10:28:42
 * @Description:
 */
import Vue from "vue";
import TextPopover from "./text-popover.vue";

const PopperIcon = Vue.extend(TextPopover);

function trigger(params) {
  const { el, binding } = params;
  const { innerText } = el.innerText;
  const { content, popperText } = binding.value;

  //el.style["-webkit-line-clamp"]
  //getComputedStyle(el).display == "-webkit-box"
  const hasWebkitBox = getComputedStyle(el).display == "-webkit-box";
  if ((hasWebkitBox && el.scrollHeight > el.offsetHeight) || el.scrollWidth > el.offsetWidth) {
    if (!el.instance || (el.instance && el.instance._isDestoryed)) {
      const popper = new PopperIcon({
        el: document.createElement("div"),
        data() {},
      });
      el.innerText = "";
      el.appendChild(popper.$el);
      el.instance = popper;
      el.instance.content = content || innerText || "";
      el.instance.popperText = popperText || content || "";
      el.instance.title = binding.value.title || "";
      el.instance.width = binding.value.width || 200;
      el.instance.placement = binding.value.placement || "top-start";
      el.instance.trigger = binding.value.trigger || "hover";
      el.instance.className = el.className;
      el.instance.style = { ...el.style };
      el.instance.style.width = "100%";
      // if (el.style["-webkit-line-clamp"]) {
      //   // el.instance.className = el.className;
      // } else {
      //   el.instance.className = el.className;
      // }
    }
  } else {
    el.innerText = binding.value.content || "";
    el.instance && el.instance.$destroy();
  }
}

export default {
  inserted(el, binding) {
    if (!el.innerText) {
      el.innerText = binding.value.content || "";
    }
  },
  bind(el, binding) {
    el.onmouseover = function () {
      if (el.instance) {
        const currentEl = el.querySelector("#popper-text");
        if (!el.instance._isDestoryed && currentEl) {
          const hasWebkitBox = getComputedStyle(currentEl).display == "-webkit-box";
          //currentEl.style["-webkit-line-clamp"]
          if (hasWebkitBox && !(currentEl.scrollHeight > currentEl.offsetHeight)) {
            el.innerText = binding.value.content || "";
            el.instance && el.instance.$destroy();
          }
          if (!hasWebkitBox && !(currentEl.scrollWidth > currentEl.offsetWidth)) {
            el.innerText = binding.value.content || "";
            el.instance && el.instance.$destroy();
          }
        } else {
          if (!currentEl) {
            el.innerText = binding.value.content || "";
            el.instance && el.instance.$destroy();
            el.instance = null;
          }
          trigger({ el, binding });
        }
        return;
      }
      trigger({ el, binding });
    };
  },
  unbind(el) {
    el.onmouseover = null;
    el.instance && el.instance.$destroy();
  },
};
